from . import models
from rest_framework import serializers
import re
from .utils import get_user_by_account
from . import models
from django.contrib.auth.hashers import make_password
from rest_framework_jwt.settings import api_settings
from django_redis import get_redis_connection


class UserMobileSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(min_length=4, max_length=6, required=True, help_text='短信验证码', write_only=True)
    token = serializers.CharField(max_length=1024, read_only=True, help_text="token认证字符串")

    class Meta:
        model = models.User
        fields = ['id', 'username', 'mobile', 'password', 'sms_code', 'token']

        extra_kwargs = {
            "id": {
                'read_only': True
            },
            "username": {
                'read_only': True
            },
            "password": {
                'write_only': True
            },
            "mobile": {
                "write_only": True
            }
        }

    def validate(self, attrs):
        mobile = attrs.get('mobile')
        sms_code = attrs.get('sms_code')
        if not re.match(r"1[3-9]\d{9}", mobile):
            raise serializers.ValidationError('对不起，手机号有误！')
        user = get_user_by_account(mobile)
        if user is not None:
            raise serializers.ValidationError("您的手机号已经注册过了！")

        # 验证码是否正确
        redis_connn = get_redis_connection('sms_code')
        redis_sms_code = redis_connn.get(f'sms_{mobile}').decode()
        if redis_sms_code != sms_code:
            raise serializers.ValidationError("验证码错误")
        return attrs

    def create(self, validated_data):
        validated_data.pop("sms_code")
        raw_password = validated_data.get('password')
        hash_password = make_password(raw_password)
        mobile = validated_data.get('mobile')
        user = models.User.objects.create(
            mobile=mobile,
            password=hash_password,
            username=mobile
        )

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)
        return user
